package practise.alogrithm.hundredInterviewQuestions.convertToConcurrent;

import practise.alogrithm.hundredInterviewQuestions.Utils.TreeBuilder;
import practise.alogrithm.hundredInterviewQuestions.Utils.TreeNode;

import java.util.concurrent.*;

/**
 * Created by xinlyu on 6/20/2014.
 */
public class GetTreeDepth extends RecursiveTask<Integer> {
    private TreeNode root;

    public GetTreeDepth(TreeNode root) {
        this.root = root;
    }

    @Override
    protected Integer compute() {
        if(root==null)
            return 0;
        GetTreeDepth left = new GetTreeDepth(root.getLeft());
        GetTreeDepth right = new GetTreeDepth(root.getRight());
        left.fork();
        right.fork();
        return Math.max(left.join(),right.join())+1;
    }

    public static void main(String[] args){
        TreeNode treeNode = TreeBuilder.createTreeByArrayInWidth(new int[]{10, 6, 14, 4, 0, 12, 16});
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        GetTreeDepth getTreeDepth = new GetTreeDepth(treeNode);
        Future<Integer> result = forkJoinPool.submit(getTreeDepth);


        try {
            System.out.println("result:" + result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
